package org.cometmi.gwt.chat.server;

import org.apache.log4j.Logger;
import org.cometmi.gwt.chat.shared.Constants;
import org.cometmi.gwt.server.annotation.ObjectMiHandler;
import org.cometmi.gwt.server.events.MiEvent;
import org.cometmi.gwt.server.events.MiEventHandler;
import org.cometmi.gwt.server.events.QueueEvent;
import org.cometmi.gwt.shared.MiQueue;
import org.cometmi.gwt.shared.exceptions.InvalidArgumentException;
import org.cometmi.gwt.shared.exceptions.NotAllowedQueueException;

@ObjectMiHandler(objectId = Constants.MESSENGER_ID, methodName = "printMessage", parameterTypes = { String.class,
		String.class }, allowedQueues = "org.cometmi.gwt.test.chat.*")
public class PrintMessageHandler implements MiEventHandler
{
	static protected Logger logger = Logger.getLogger(PrintMessageHandler.class);

	@Override
	public void onBeforeMethod(MiEvent event)
	{
		try
		{
			String msg = event.getMethodArgument(String.class, 0);
			String[] msgParts = msg.split("::");

			if (msgParts.length == 2)
			{
				String sender = event.getMethodArgument(String.class, 1);
				String[] users = msgParts[0].split("(\\s*,\\s*)");
				QueueEvent sourceQEvent = event.getTargetQueueEvent();

				MiQueue sourceQueue = sourceQEvent.getSourceQueue();
				String targetUserName = sourceQueue.getAttribute("userName", null);

				boolean enabled = false;

				logger.debug("[ChatFilter] Queue owner: " + targetUserName);
				logger.debug("[ChatFilter] Target users: " + msgParts[0]);

				if (targetUserName.equals(sender))
				{
					event.setMethodArgument(msgParts[1], 0);
					event.setMethodArgument("(private message for " + msgParts[0] + ")", 1);
					enabled = true;
				}
				else
					for (int i = 0; i < users.length; i++)
						if (users[i].equals(targetUserName))
						{
							event.setMethodArgument(msgParts[1], 0);
							event.setMethodArgument("(private message from " + sender + ")", 1);
							enabled = true;

							break;
						}

				event.setEnabled(enabled);
			}
		}
		catch (InvalidArgumentException e)
		{}
		catch (NotAllowedQueueException e)
		{}
	}

	@Override
	public void onAfterMethod(MiEvent event)
	{}
}
